<template>
  <el-dialog
    v-model="props.visible"
    width="auto"
    destroy-on-close
    align-center
    :close-on-click-modal="false"
    @opened="handleDeviceDialogOpen"
    @close="handleDeviceDialogClose"
    title="设备选择">
    <div class="device-dialog">
      <div class="device-map">
        <div
          class="map-container"
          id="deviceMap"></div>
      </div>
      <div class="btn-group">
        <el-button @click="handleDeviceDialogClose">返回</el-button>
        <el-button
          type="primary"
          @click="sendDeviceIds"
          >确认</el-button
        >
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
  import { getCurrentInstance, ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
  import markerIcon from '@/assets/img/liveData/mapPin.png'
  import highlightMarkerIcon from '@/assets/img/liveData/mapPinHL.png'
  import MapInit from '@/utils/mineMap/MapInit'
  import tipMessage from '@/utils/tipMessage'

  const emit = defineEmits(['handleDeviceDialogClose', 'getDeviceIds'])
  const { proxy } = getCurrentInstance()
  const props = defineProps({
    visible: {
      type: Boolean,
      default: false
    },
    selectedDevices: {
      type: Array,
      default: []
    }
  })
  const mapObject = {
    darkMapObj: null,
    mapCenter: [],
    marker: null
  }
  const deviceGeoData = ref([])
  const selectedDeviceIds = ref([])
  const mapImgsList = [
    { src: markerIcon, id: 'markerIcon' },
    { src: highlightMarkerIcon, id: 'highlightMarkerIcon' }
  ]
  /* ========方法======== */
  const getDeviceMap = async () => {
    try {
      const res = await proxy.$http.postWithBody('device/query', {
        reviewStatus: 1
      })
      getDeviceGeoData(res.list)
      initMap()
    } catch (error) {
      console.log(error)
    }
  }
  const getDeviceGeoData = list => {
    deviceGeoData.value = {
      type: 'FeatureCollection',
      features: []
    }
    deviceGeoData.value.features = list.map(item => ({
      type: 'Feature',
      geometry: {
        type: 'Point',
        coordinates: [item.longitude, item.latitude]
      },
      properties: {
        ...item,
        isSelected: props.selectedDevices.indexOf(item.deviceId) > -1 ? true : false
      }
    }))
  }

  const initMap = () => {
    mapObject.darkMapObj = new MapInit('deviceMap', {
      center: [114.88923193324109, 40.76546125305629]
    })
    mapObject.darkMapObj.loadMapImgs(mapImgsList)
    mapObject.darkMapObj.on('load', () => {
      drawDeviceMaker()
    })
    mapObject.darkMapObj.on('click', 'deviceMarkerLayer', selectDeviceMarker)
  }
  const selectDeviceMarker = e => {
    let features = mapObject.darkMapObj.queryRenderedFeatures(e.point, { layers: ['deviceMarkerLayer'] })
    if (features?.length > 0) {
      const { properties } = features[0]
      if (properties.isSelected) {
        deviceGeoData.value.features.forEach(item => {
          if (item.properties.deviceId === properties.deviceId) {
            item.properties.isSelected = false
          }
        })
        selectedDeviceIds.value = selectedDeviceIds.value.filter(item => item !== properties.deviceId)
      } else {
        deviceGeoData.value.features.forEach(item => {
          if (item.properties.deviceId === properties.deviceId) {
            item.properties.isSelected = true
          }
        })
        selectedDeviceIds.value.push(properties.deviceId)
      }
      mapObject.darkMapObj.getSource('deviceMarkerSrc').setData(deviceGeoData.value)
    }
  }
  const drawDeviceMaker = () => {
    addDeviceMarkerLayerSrc()
    addDeviceMarkerLayer()
  }
  const addDeviceMarkerLayerSrc = () => {
    mapObject.darkMapObj.addSource('deviceMarkerSrc', {
      type: 'geojson',
      data: deviceGeoData.value,
      generateId: true
    })
  }
  const addDeviceMarkerLayer = () => {
    mapObject.darkMapObj.addLayer({
      id: 'deviceMarkerLayer',
      type: 'symbol',
      source: 'deviceMarkerSrc',
      layout: {
        // 'icon-image': 'markerIcon',
        'icon-image': ['case', ['==', ['get', 'isSelected'], true], 'highlightMarkerIcon', 'markerIcon'],
        'icon-size': 0.5
      }
    })
  }
  const handleDeviceDialogOpen = () => {
    getDeviceMap()
  }
  const handleDeviceDialogClose = () => {
    selectedDeviceIds.value = []
    emit('handleDeviceDialogClose', false)
  }
  const sendDeviceIds = () => {
    emit('getDeviceIds', selectedDeviceIds.value)
    handleDeviceDialogClose()
  }

  onMounted(() => {})
  onBeforeUnmount(() => {
    if (mapObject.darkMapObj) {
      mapObject.darkMapObj.remove()
    }
  })
</script>

<style scoped lang="scss">
  .device-dialog {
    width: pxTvw(1200);
    display: flex;
    flex-wrap: wrap;
    justify-content: center;

    & > .device-map {
      width: pxTvw(1168);
      height: pxTvh(658);
      margin-top: pxTvh(16);
      & > .map-container {
        @include wh100();
      }
    }

    & > .btn-group {
      margin-top: pxTvh(24);
      display: flex;
      justify-content: end;
      margin-right: pxTvh(20);
      margin-left: auto;
    }
  }
</style>
